<template>
  <view class="medication-container">
    <!-- 顶部用户信息栏 -->
    <view class="user-header">
      <view class="user-info">
        <text class="welcome-text">{{userName}}的用药管理</text>
       <!-- <view class="date-filter">
          <text 
            v-for="(filter, index) in timeFilters" 
            :key="index"
            :class="{ 'filter-active': activeTimeFilter === index }"
            @click="changeTimeFilter(index)"
          >
            {{filter}}
          </text>
        </view> -->
      </view>
    </view>

    <!-- 操作按钮组 -->
    <view class="action-buttons">
      <button class="btn remind-btn" @click="sendReminders">
        <u-icon name="bell" color="#fff" size="18"></u-icon>
        一键提醒
      </button>
      <button class="btn edit-btn" @click="toggleEditMode">
        <u-icon :name="isEditMode ? 'checkmark' : 'edit-pen'" color="#fff" size="18"></u-icon>
        {{isEditMode ? '完成编辑' : '编辑用药'}}
      </button>
    </view>

    <!-- 分类标签 -->
    <scroll-view class="category-tabs" scroll-x>
      <text 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="{active: activeTab === index}"
        @click="activeTab = index"
      >
        {{tab}}
      </text>
    </scroll-view>

    <!-- 用药提醒卡片 -->
    <view 
      class="medication-card"
      v-for="(category, catIndex) in filteredMedications"
      :key="catIndex"
    >
      <view class="card-header">
        <view class="time-badge">
          <text>{{category.time}}</text>
        </view>
        <text class="card-title">{{category.type}}用药</text>
        <text class="edit-time" v-if="isEditMode" @click="editTime(catIndex)">
          <u-icon name="edit-pen" size="18" color="#1989fa"></u-icon>
        </text>
      </view>

      <!-- 用药列表 -->
      <view class="medication-list">
        <view 
          class="medication-item" 
          v-for="(item, index) in category.list" 
          :key="index"
          @click="isEditMode ? showEditDialog(catIndex, index) : toggleStatus(catIndex, index)"
        >
          <view class="medication-info">
            <text class="medication-name">{{item.name}}</text>
            <view class="medication-details">
              <text class="medication-dose">{{item.dose}}</text>
              <text class="medication-frequency">{{item.frequency}}</text>
            </view>
          </view>
          
          <view class="status-indicator" :class="item.status">
            <u-icon 
              :name="item.status === 'taken' ? 'checkmark-circle-fill' : 'clock'"
              :color="item.status === 'taken' ? '#07c160' : '#1989fa'" 
              size="36"
            ></u-icon>
            <text class="status-text">{{item.status === 'taken' ? '已服用' : '待服用'}}</text>
          </view>
          
          <u-icon 
            v-if="isEditMode"
            name="trash" 
            color="#f56c6c" 
            size="20"
            @click.stop="deleteMedication(catIndex, index)"
            class="delete-icon"
          ></u-icon>
        </view>
      </view>
    </view>

    <!-- 添加/编辑用药弹窗 -->
    <u-popup v-model="showAddDialog" mode="center" round="16" border-radius="16">
      <view class="dialog-container">
        <text class="dialog-title">{{isEditing ? '编辑用药' : '添加用药'}}</text>
        
        <view class="form-item">
          <text class="form-label">药品名称</text>
          <uni-easyinput 
            v-model="currentMedication.name" 
            placeholder="请输入药品名称"
            border="none"
            bg-color="#f5f7fa"
            height="80"
            placeholder-style="color: #c0c4cc"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">剂量</text>
          <uni-easyinput 
            v-model="currentMedication.dose" 
            placeholder="如：10mg"
            border="none"
            bg-color="#f5f7fa"
            height="80"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">用药频率</text>
          <uni-easyinput 
            v-model="currentMedication.frequency" 
            placeholder="如：每日2次"
            border="none"
            bg-color="#f5f7fa"
            height="80"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">药品类型</text>
          <u-radio-group 
            v-model="currentMedication.category"
            placement="row"
            active-color="#1989fa"
          >
            <u-radio 
              v-for="(tab, index) in tabs" 
              :key="index"
              :name="tab"
              :disabled="index === 0"
              label-size="16"
            >
              {{tab}}
            </u-radio>
          </u-radio-group>
        </view>
        
        <view class="form-item">
          <text class="form-label">用药时间</text>
          <picker 
            mode="selector" 
            :range="timeOptions" 
            @change="(e) => currentMedication.time = timeOptions[e.detail.value]"
          >
            <view class="picker">
              <text>{{currentMedication.time || '请选择用药时间'}}</text>
              <u-icon name="arrow-down" color="#c0c4cc" size="16"></u-icon>
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="form-label">用药日期</text>
          <picker 
            mode="date" 
            :value="currentMedication.date"
            @change="(e) => currentMedication.date = e.detail.value"
          >
            <view class="picker">
              <text>{{currentMedication.date || '请选择用药日期'}}</text>
              <u-icon name="arrow-down" color="#c0c4cc" size="16"></u-icon>
            </view>
          </picker>
        </view>
        
        <view class="dialog-buttons">
          <button class="btn cancel-btn" @click="showAddDialog = false">取消</button>
          <button class="btn confirm-btn" @click="saveMedication">确认</button>
        </view>
      </view>
    </u-popup>
    
    <!-- 修改时间弹窗 -->
    <uni-popup v-model="showTimeDialog" mode="center" round="16">
      <view class="time-dialog">
        <text class="dialog-title">修改用药时间</text>
        <picker 
          mode="selector" 
          :range="timeOptions" 
          @change="(e) => newTime = timeOptions[e.detail.value]"
        >
          <view class="picker">
            <text>{{newTime || '请选择新的用药时间'}}</text>
            <uni-icons name="arrow-down" color="#c0c4cc" size="16"></uni-icons>
          </view>
        </picker>
        <view class="dialog-buttons">
          <button class="btn cancel-btn" @click="showTimeDialog = false">取消</button>
          <button class="btn confirm-btn" @click="updateTime">确认</button>
        </view>
      </view>
    </uni-popup>
    
    <!-- 添加用药按钮 -->
    <view class="add-medication-btn" @click="showAddDialog = true" v-if="!isEditMode">
      <uni-icons name="plus" color="#fff" size="24"></uni-icons>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';

const userName = ref('张患者');
const activeTab = ref(0);
const activeTimeFilter = ref(0);
const isEditMode = ref(false);
const showAddDialog = ref(false);
const showTimeDialog = ref(false);
const isEditing = ref(false);
const newTime = ref('');
const editingIndex = ref(null);
const editingCatIndex = ref(null);

const tabs = ref(['全部', '口服药', '注射药', '外用药']);
// const timeFilters = ref(['今日', '本周', '本月']);
const timeOptions = ref(['早餐前', '早餐后', '午餐前', '午餐后', '晚餐前', '晚餐后', '睡前']);

// 当前编辑的用药数据
const currentMedication = ref({
  name: '',
  dose: '',
  frequency: '',
  category: '口服药',
  time: '早餐后',
  date: getTodayDate(),
  status: 'pending'
});

// 获取今天日期的字符串格式
function getTodayDate() {
  const today = new Date();
  return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
}

// 模拟数据
const medicineData = ref([
  {
    type: '口服药',
    time: '早餐后',
    date: getTodayDate(),
    list: [
      { name: '硝苯地平', dose: '10mg', frequency: '每日1次', status: 'taken' },
      { name: '氢氯噻嗪', dose: '25mg', frequency: '每日1次', status: 'pending' }
    ]
  },
  {
    type: '口服药', 
    time: '午餐前',
    date: getTodayDate(),
    list: [
      { name: '二甲双胍', dose: '0.5g', frequency: '每日2次', status: 'pending' }
    ]
  },
  {
    type: '注射药',
    time: '晚餐后',
    date: getTodayDate(),
    list: [
      { name: '胰岛素', dose: '10单位', frequency: '每日1次', status: 'taken' }
    ]
  },
  {
    type: '外用药',
    time: '睡前',
    date: '2023-05-10',
    list: [
      { name: '皮炎平', dose: '适量', frequency: '每日1次', status: 'taken' }
    ]
  }
]);

// 时间筛选处理
const changeTimeFilter = (index) => {
  activeTimeFilter.value = index;
};

// 分类筛选
const filteredMedications = computed(() => {
  let result = [...medicineData.value];
  const today = new Date();
  const todayStr = getTodayDate();
  
  // 按类型筛选
  if (activeTab.value > 0) {
    result = result.filter(item => item.type === tabs.value[activeTab.value]);
  }
  
  // 按时间筛选
  if (activeTimeFilter.value === 1) { // 本周
    // 获取本周一的日期
    const monday = new Date(today);
    monday.setDate(today.getDate() - today.getDay() + (today.getDay() === 0 ? -6 : 1));
    const mondayStr = monday.toISOString().split('T')[0];
    
    // 获取本周日的日期
    const sunday = new Date(monday);
    sunday.setDate(monday.getDate() + 6);
    const sundayStr = sunday.toISOString().split('T')[0];
    
    result = result.filter(item => {
      return item.date >= mondayStr && item.date <= sundayStr;
    });
  } 
  else if (activeTimeFilter.value === 2) { // 本月
    const firstDay = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-01`;
    const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0).getDate();
    const lastDayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`;
    
    result = result.filter(item => {
      return item.date >= firstDay && item.date <= lastDayStr;
    });
  }
  else if (activeTimeFilter.value === 0) { // 今日
    result = result.filter(item => item.date === todayStr);
  }
  
  return result;
});

// 切换编辑模式
const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value;
};

// 显示编辑对话框
const showEditDialog = (catIndex, medIndex) => {
  isEditing.value = true;
  editingCatIndex.value = catIndex;
  editingIndex.value = medIndex;
  currentMedication.value = {...medicineData.value[catIndex].list[medIndex]};
  currentMedication.value.category = medicineData.value[catIndex].type;
  showAddDialog.value = true;
};

// 保存用药
const saveMedication = () => {
  const medData = {...currentMedication.value};
  
  if (isEditing.value) {
    // 更新现有用药
    medicineData.value[editingCatIndex.value].list[editingIndex.value] = medData;
  } else {
    // 添加新用药
    const categoryIndex = medicineData.value.findIndex(
      item => item.type === medData.category && item.time === medData.time && item.date === medData.date
    );
    
    if (categoryIndex >= 0) {
      // 已有相同类型、时间和日期的分类
      medicineData.value[categoryIndex].list.push(medData);
    } else {
      // 新建分类
      medicineData.value.push({
        type: medData.category,
        time: medData.time,
        date: medData.date,
        list: [medData]
      });
    }
  }
  
  resetDialog();
};

// 删除用药
const deleteMedication = (catIndex, medIndex) => {
  medicineData.value[catIndex].list.splice(medIndex, 1);
  
  // 如果分类下没有用药，删除整个分类
  if (medicineData.value[catIndex].list.length === 0) {
    medicineData.value.splice(catIndex, 1);
  }
};

// 修改用药时间
const editTime = (catIndex) => {
  editingCatIndex.value = catIndex;
  newTime.value = medicineData.value[catIndex].time;
  showTimeDialog.value = true;
};

const updateTime = () => {
  medicineData.value[editingCatIndex.value].time = newTime.value;
  showTimeDialog.value = false;
};

// 切换用药状态
// const toggleStatus = (catIndex, medIndex) => {
//   const item = medicineData.value[catIndex].list[medIndex];
//   item.status = item.status === 'taken' ? 'pending' : 'taken';
// };

// 一键提醒功能
const sendReminders = () => {
  const pendingMeds = medicineData.value.flatMap(category => category.list).filter(item => item.status === 'pending');
  
  if (pendingMeds.length === 0) {
    uni.showToast({
      title: '没有待服用的药品',
      icon: 'none'
    });
    return;
  }
  
  uni.showModal({
    title: '发送用药提醒',
    content: `确定要发送${pendingMeds.length}条用药提醒给患者吗？`,
    success: (res) => {
      if (res.confirm) {
        // 这里实际应该调用接口发送提醒
        uni.showToast({
          title: '提醒已发送',
          icon: 'success'
        });
        
        // 模拟标记为已提醒状态
        pendingMeds.forEach(item => {
          item.status = 'taken';
        });
      }
    }
  });
};

// 重置对话框
const resetDialog = () => {
  showAddDialog.value = false;
  isEditing.value = false;
  currentMedication.value = {
    name: '',
    dose: '',
    frequency: '',
    category: '口服药',
    time: '早餐后',
    date: getTodayDate(),
    status: 'pending'
  };
};
</script>

<style lang="scss" scoped>
.medication-container {
  padding: 24rpx;
  background-color: #f5f7fa;
  min-height: 100vh;
  position: relative;
  padding-bottom: 120rpx;
}

.user-header {
  margin-bottom: 24rpx;
  
  .user-info {
    .welcome-text {
      font-size: 36rpx;
      font-weight: 500;
      color: #303133;
      margin-bottom: 24rpx;
      display: block;
    }
    
    .date-filter {
      display: flex;
      gap: 32rpx;
      
      text {
        color: #909399;
        font-size: 28rpx;
        position: relative;
        padding-bottom: 8rpx;
        
        &.filter-active {
          color: #1989fa;
          font-weight: 500;
          
          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 4rpx;
            background: #1989fa;
            border-radius: 2rpx;
          }
        }
      }
    }
  }
}

.action-buttons {
  display: flex;
  gap: 20rpx;
  margin-bottom: 24rpx;
  
  .btn {
    flex: 1;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    border-radius: 12rpx;
    border: none;
    
    &.remind-btn {
      background: linear-gradient(135deg, #ff976a, #ff6600);
      box-shadow: 0 4rpx 12rpx rgba(255, 151, 106, 0.2);
    }
    
    &.edit-btn {
      background: linear-gradient(135deg, #1989fa, #36a4f1);
      box-shadow: 0 4rpx 12rpx rgba(25, 137, 250, 0.2);
    }
  }
}

.category-tabs {
  white-space: nowrap;
  margin-bottom: 24rpx;
  
  text {
    display: inline-block;
    padding: 12rpx 24rpx;
    margin-right: 16rpx;
    font-size: 26rpx;
    color: #606266;
    background-color: #fff;
    border-radius: 24rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    
    &:last-child {
      margin-right: 0;
    }
    
    &.active {
      color: #1989fa;
      background-color: #e8f4ff;
      font-weight: 500;
    }
  }
}

.medication-card {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  
  .card-header {
    display: flex;
    align-items: center;
    padding: 24rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .time-badge {
      background: #e8f4ff;
      padding: 6rpx 16rpx;
      border-radius: 8rpx;
      margin-right: 16rpx;
      
      text {
        color: #1989fa;
        font-size: 24rpx;
        font-weight: 500;
      }
    }
    
    .card-title {
      font-size: 30rpx;
      font-weight: 500;
      color: #303133;
    }
    
    .edit-time {
      margin-left: auto;
    }
  }
}

.medication-list {
  padding: 0 24rpx;
  
  .medication-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 28rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
    position: relative;
    
    &:last-child {
      border-bottom: none;
    }
    
    .medication-info {
      flex: 1;
      .medication-name {
        display: block;
        font-size: 30rpx;
        font-weight: 500;
        color: #303133;
        margin-bottom: 8rpx;
      }
      
      .medication-details {
        display: flex;
        gap: 20rpx;
        
        text {
          font-size: 26rpx;
          color: #909399;
        }
      }
    }
    
    .status-indicator {
      display: flex;
      flex-direction: column;
      align-items: center;
      min-width: 100rpx;
      
      .status-text {
        font-size: 24rpx;
        margin-top: 8rpx;
      }
      
      &.taken .status-text {
        color: #67c23a;
      }
      
      &.pending .status-text {
        color: #1989fa;
      }
    }
    
    .delete-icon {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      padding: 16rpx;
    }
  }
}

.dialog-container, .time-dialog {
  padding: 40rpx;
  width: 640rpx;
  background: white;
  
  .dialog-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #303133;
    margin-bottom: 32rpx;
    display: block;
    text-align: center;
  }
}

.form-item {
  margin-bottom: 32rpx;
  
  .form-label {
    display: block;
    font-size: 28rpx;
    color: #606266;
    margin-bottom: 16rpx;
  }
  
  .picker {
    padding: 20rpx;
    background-color: #f5f7fa;
    border-radius: 8rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    text {
      color: #606266;
    }
  }
}

.dialog-buttons {
  display: flex;
  gap: 20rpx;
  margin-top: 40rpx;
  
  .btn {
    flex: 1;
    height: 80rpx;
    border-radius: 8rpx;
    font-size: 28rpx;
    border: none;
    
    &.cancel-btn {
      background-color: #f5f5f5;
      color: #606266;
    }
    
    &.confirm-btn {
      background: linear-gradient(135deg, #1989fa, #36a4f1);
      color: white;
    }
  }
}

.time-dialog {
  padding: 40rpx;
  width: 560rpx;
  
  .dialog-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #303133;
    margin-bottom: 32rpx;
    text-align: center;
  }
  
  .picker {
    padding: 24rpx;
    background-color: #f5f7fa;
    border-radius: 8rpx;
    margin-bottom: 32rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.add-medication-btn {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #1989fa, #36a4f1);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 20rpx rgba(25, 137, 250, 0.3);
  z-index: 10;
}
</style>